package wyd

import com.google.appengine.api.datastore.DatastoreServiceFactory
import com.google.appengine.api.datastore.Entity
import com.google.appengine.api.datastore.FetchOptions
import com.google.appengine.api.datastore.PreparedQuery
import com.google.appengine.api.datastore.Query

import groovyx.gaelyk.GaelykCategory

import java.util.Date

public class WydCategory {

	public static long getNextAutoNumber(String id) {
		def query = new Query('AutoNumberE')
		query.addFilter('id', Query.FilterOperator.EQUAL, id)
		PreparedQuery preparedQuery = DatastoreServiceFactory.datastoreService.prepare(query)
		def entities = preparedQuery.asList(FetchOptions.Builder.withLimit(1))

		Entity an = null
		Date now = new Date()
		if(entities.size() == 0) {
			an = new Entity('AutoNumberE')
			an.id = id
			an.value = 1
			an.createdTime = now
			an.updatedTime = now
		}
		else {
			an = entities[0]
			an.value += 1
			an.updatedTime = now
		}
		GaelykCategory.save(an)

		return an.value
	}
}
